<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\general\LihuaCity;
use app\common\model\goods\LihuaGoods;
use app\common\model\LihuaUseraddr;
use app\common\model\LihuaActivity; //城市活动表

/**
 * 购物车
 */
class Cart extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 购物车主页
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID")
     * @ApiParams   (name="store_id", type="int", required=true, description="门店ID")
     * @ApiParams   (name="goods_nums", type="string", required=true, description="商品ID及数量键值对JSON字符串")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1573029605","data":{"goods":[{"id":43,"category_id":57,"name":"蛋花汤料","short_name":"蛋花汤","description":"含汤碗 净含量8克（配餐产品，不单独售卖）","pic":"http://image.lihua.com/images/newweb/2016/09/thumb_57cfc743835e0.jpg","price":2,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":0,"enable_stock":0,"num":3,"num_price":6},{"id":44,"category_id":57,"name":"三件套","short_name":"三件套","description":"三件套（不含汤勺，配餐产品，不单独售卖）","pic":"http://image.lihua.com/images/newweb/2018/12/thumb_5c0f521445dd8.JPG","price":2.5,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":0,"enable_stock":0,"num":1,"num_price":2.5}],"goods_nums":{"43":3,"44":1},"goods_stocks":null,"goods_amount":8.5,"packing_fee":0,"enough_fee":0,"subtotal":8.5,"discount":0,"submit":0,"error":"请选择一份主食，配餐商品单点不送"}})
     */
    public function index()
    {
        $this->request->filter('trim,strip_tags');
        $city_id    = (int)$this->request->post('city_id', 0);
        $store_id   = (int)$this->request->post('store_id', 0);
        if (!$city_id || !$store_id) $this->error('非法操作');

        $city = LihuaCity::getCityInfo($city_id);
        if (!$city) $this->error('非法操作');

        $goods_nums = $this->request->post('goods_nums', '');
        if ($goods_nums) {
            $goods_nums = json_decode($goods_nums, true);
            if (json_last_error()) $this->error('非法操作');
        } else {
            $goods_nums = [];
        }

        $data = LihuaGoods::getCartGoodsList($store_id, $goods_nums);
        //城市满减
        $enough = LihuaCity::countEnough($city['enough'], $data['goods_amount']);

        $actfree = [
            'half'          => [], //第二份半价
            'sales'         => [], //促销商品
            'half_free'     => 0,  //第二份半价优惠费用
            'sales_free'    => 0,  //促销商品优惠会用
            'half_mutex'    => 0,  //半价活动是否互斥
            'sales_mutex'   => 0,  //半价活动是否互斥
            'enough_reduce' => 0,  //满减优惠金额
        ];

        //计算城市活动优惠
        if ($this->token) {
            $user_id  = $this->auth->id;
            $actfree = LihuaActivity::computingOffers($city_id, $data, $user_id, 1, 1, $store_id);
            if( $actfree['half_free']>0 || $actfree['sales_free']>0 ) { //如果第二份半价和促销商品有优惠则不能使用满减优惠
                if($actfree['half_mutex']==1 && $actfree['half_free']>0){ //活动互斥的情况下才会将满减的优惠删除
                    $enough['reduce'] = 0;
                }
                if($actfree['sales_mutex']==1 && $actfree['sales_free']>0){ //活动互斥的情况下才会将满减的优惠删除
                    $enough['reduce'] = 0;
                }
            }
        }
        $actfree['enough_reduce'] = (int)$enough['reduce'];
        $discount = round($actfree['half_free'] + $actfree['sales_free'] + $enough['reduce'], 2);//已优惠
        $subtotal = round($data['goods_amount'] - $discount, 2);//小计
        $data['enough_fee'] = $enough['reduce'];
        $data['subtotal'] = $subtotal;
        $data['discount'] = $discount;

        //结算
        if (!$data['alone_sale']) {
            $submit = 0;
            $error  = '请选择一份主食，配餐商品单点不送';
        } elseif ($data['lack_goods']['ids']) {
            $submit = 0;
            $error  = join('、', $data['lack_goods']['names']) . ' 库存不足';
        } elseif ($data['goods_amount'] < $city['min_price']) {
            $submit = 0;
            $error  = '商品起送价￥' . $city['min_price'];
        } else {
            $submit = 1;//为1可提交结算
            $error  = '';
        }

        $data['actinfo'] = $actfree;
        $data['submit'] = $submit;
        $data['error']  = $error;
        
        // unset($data['alone_sale'], $data['lack_goods']);
        $this->success('OK', $data);
    }

    /**
     * 商品结算
     *
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求Token，游客不传")
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID")
     * @ApiParams   (name="store_id", type="int", required=true, description="门店ID")
     * @ApiParams   (name="goods_nums", type="string", required=true, description="商品ID及数量键值对JSON字符串")
     * @ApiParams   (name="platform", type="string", required=true, description="平台，默认为app")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1573029992","data":{"useraddr":{"id":373694,"consignee":"吴大帝","mobile":"13961259811","address":"中吴大道777号308","name":"金龙大厦","house_num":"15幢37号"},"goods":[{"id":1180,"category_id":1,"name":"冬菇滑鸡饭","short_name":"冬菇滑鸡饭","description":"冬菇滑鸡 蒜泥毛白菜 五仁酱丁萝卜干送冰红茶（图片仅供参考）","pic":"https://lihua.czapi.cn/uploads/goods/2019/10/20725d9efea561b3e.jpg","price":0.01,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":1,"enable_stock":1,"num":2,"num_price":0.02},{"id":10015,"category_id":218,"name":"特别的爱砂锅","short_name":"特爱砂锅","description":"六荤六素全家福","pic":"http://image.lihua.com/images/newweb/2019/08/thumb_5d5b494cbe158.jpg","price":25,"box_fee":1,"limit_num":1,"at_least":1,"is_alone_sale":1,"enable_stock":1,"num":1,"num_price":25}],"goods_nums":{"1180":2,"10015":1},"goods_stocks":{"1180":5000,"10015":1000},"goods_amount":25.02,"packing_fee":1,"deliver_fee":3,"enough_fee":0,"original_amount":29.02,"order_amount":29.02,"discount":0}})
     */
    public function settle()
    {
        $this->request->filter('trim,strip_tags');
        $city_id    = (int)$this->request->post('city_id', 0);
        $store_id   = (int)$this->request->post('store_id', 0);
        $goods_nums = $this->request->post('goods_nums', '');
        $platform   = strtolower($this->request->post('platform', 'app'));
        $use_half_Free = (int)$this->request->post('use_half_free', 1);//是否选择支持活动优惠
        $use_sales_free = (int)$this->request->post('use_sales_free', 1);//是否选择支持活动优惠
        $city_enough    = (int)$this->request->post('city_enough', 1);//是否使用城市满减

        if (!in_array($platform, ['app', 'xcx'])) $this->error('非法操作');
        if (!$city_id) $this->error('您所在的位置，对应门店已经暂停营业，请重新选择其他门店，或者致电客服热线');
        if (!$store_id) $this->error('您所在的位置，对应门店已经暂停营业，手动选择其他门店为您配送');
        if (!$goods_nums) $this->error('请选择商品');
        $goods_nums = json_decode($goods_nums, true);
        if (json_last_error()) $this->error('非法操作');

        // $store = \app\common\model\general\LihuaStore::getById($store_id);
        // if ($store['status'] == 0) $this->error('对应门店已经休假,请选择其他收餐地址');

        $data = [];

        $user_id  = 0;
        if ($this->token) {
            $user_id  = (int)$this->auth->id;
        }

        //收货地址
        $data['useraddr'] = LihuaUseraddr::where(['user_id' => $user_id, 'store_id' => $store_id])
            ->field('id,consignee,mobile,address,name,house_num')->find();

        //城市信息
        $city = LihuaCity::getCityInfo($city_id);

        //计算是否需要餐具收费，如果餐具收费则计算用户需要多少餐具
        if($city['need_tableware_fee']==1){
            $tableware_id = $city['tableware_id'];
            //用户自定义餐具数量
            $tableware_num = (int)$this->request->post('tableware_num', -1);
            //查看$tableware_num是否为0 ，如果为0 ，则查询购物车里面是否包含餐具商品
            if($tableware_num==-1) {
                if(isset($goods_nums[$tableware_id])){
                    if($goods_nums[$tableware_id]>0){
                        $tableware_num = $goods_nums[$tableware_id];
                    }
                }
            }
            $goods_nums[$tableware_id] = $tableware_num;
        }
        
        //商品列表
        $goods = LihuaGoods::getCartGoodsList($store_id, $goods_nums, $user_id);
        if (!$goods['alone_sale']) $this->error('请选择一份主食，配餐商品单点不送');
        if ($goods['lack_goods']['ids']) $this->error(join('、', $goods['lack_goods']['names']) . ' 库存不足');

        $data = array_merge($data, $goods);
        
        if (!$city) $this->error('非法操作');

        if($user_id==29271||$user_id==17){
            //
        }else{
            if ($goods['goods_amount'] < $city['min_price']) $this->error('商品起送价￥' . $city['min_price']);
        }

        $data['deliver_fee'] = round($city['deliver_fee'], 2);

        $enough = ['name'=>'','reduce'=>0];
        if($city_enough==1){
            //城市满减
            $enough = LihuaCity::countEnough($city['enough'], $goods['goods_amount']);
        }

        $res_invoice = '';
        $cityname = $city['city_name'];
        if($cityname=='上海'||$cityname=='苏州'||$cityname=='广州'){
            $res_invoice = "发票";
        }
        if($cityname=='常州'||$cityname=='无锡'||$cityname=='南京'||$cityname=='北京'){
            $res_invoice = "电子发票";
        }

        $actfree = [
            'half'          => [], //第二份半价
            'sales'         => [], //促销商品
            'half_free'     => 0,  //第二份半价优惠费用
            'sales_free'    => 0,  //促销商品优惠会用
            'half_mutex'    => 0,  //半价活动是否互斥
            'sales_mutex'   => 0,  //半价活动是否互斥
            'enough_reduce' => 0,  //满减优惠金额
        ];

        //计算城市活动优惠
        if ($this->token) {
            $user_id  = $this->auth->id;
            $actfree = LihuaActivity::computingOffers($city_id, $data, $user_id, $use_half_Free, $use_sales_free, $store_id);
            if( $actfree['half_free']>0 || $actfree['sales_free']>0 ) { //如果第二份半价和促销商品有优惠则不能使用满减优惠
                if($actfree['half_mutex']==1 && $actfree['half_free']>0){ //活动互斥的情况下才会将满减的优惠删除
                    $enough['reduce'] = 0;
                }
                if($actfree['sales_mutex']==1 && $actfree['sales_free']>0){ //活动互斥的情况下才会将满减的优惠删除
                    $enough['reduce'] = 0;
                }
            }
        }
        $actfree['enough_reduce'] = (int)$enough['reduce'];
        $data['enough_fee'] = $enough['reduce'];

        //订单金额
        $discount = abs(round($actfree['half_free'] + $actfree['sales_free'] + $enough['reduce'], 2));//已优惠

        $data['packing_fee_bnk'] = $data['packing_fee'];
        //城市满额免配送费
        $amount_dis = round($goods['goods_amount'] - $discount, 2);

        if($city_id==3){
            if($amount_dis<$city['min_price']){
                $this->error('商品价格不满'.$city['min_price'].'元起送价');
            }
        }
        
        if($city['feeprice']>0){
            if($amount_dis>=$city['feeprice']){
                $data['deliver_fee'] = 0;
            }
        }
        //城市满额免餐盒费
        if($city['feepacking']>0){
            if($amount_dis>=$city['feepacking']){
                $data['packing_fee'] = 0;
            }
        }
        
        $original_amount         = round($goods['goods_amount'] + $data['packing_fee'] + $data['deliver_fee'], 2);
        $data['original_amount'] = $original_amount;
        $data['order_amount']    = round($original_amount - $discount, 2);
        $data['discount']        = $discount;
        $data['actinfo']         = $actfree;
        $data['res_invoice']     = $res_invoice;

        unset($data['alone_sale'], $data['lack_goods']);
        $this->success('OK', $data);
    }

}
